<?php
namespace App\Http\Controllers\Es;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Es\EsController;
use App\Http\Controllers\Es\GetDataController;
use Exception;
use Illuminate\Http\Request;

//https://www.elastic.co/guide/cn/elasticsearch/php/current/_overview.html

class TestController extends Controller
{
    public $resultJson = null;
    public function __construct()
    {
        if(empty($resultJson))
        {
            $this->resultJson = app('resultJson');
        }
    }

    public function getClusterStatus()
    {
        $response =  array();
        try{
            $response = EsController::getInstance()->getClusterStatus();
        }
        catch (Exception $exception)
        {
            $this->resultJson->setMessage($exception->getMessage());
        }
        finally{
            $this->resultJson->setData($response)->errorJson();
        }
    }

    public function allocationExplain()
    {
        $response =  array();
        try{
            $response = EsController::getInstance()->getAllocationExplain();
        }
        catch (Exception $exception)
        {
            $response = json_decode($exception->getMessage(),true);
            $this->resultJson->setMessage($response)->setCode($exception->getCode());
        }
        finally{
            $this->resultJson->setData($response)->errorJson();
        }
    }


    public function putMapping()
    {
        $soure = [
            'uniquekey'=>	'新闻ID',
            'title'=>'新闻标题',
            'date'=>'新闻时间',
            'category'=>'新闻分类',
            'author_name'=>'新闻来源',
            'url'=>'新闻访问链接',
            'thumbnail_pic'=>'新闻图片链接',
            'is_content'=>'是否有新闻内容,1表示有'
        ];
        $params = [
            'index' => 'news',
            'type' => 'top',
            'body' => [
                'top' => [
                    '_source'=>[
                        'enabled' => true      //include，excludes
                    ],
                    'dynamic' => false,     //是否改变插入新的字段是否改变字段结构
                    'properties' => [
                        'title' => [
                            'type' => 'text',  //store 独立存储一份数据
                            'index' => true, //false(analyzed)  doc_values和fielddata就是用来给文档建立正排索引的 https://segmentfault.com/a/1190000021668629
                            'analyzer' => 'ik_max_word' ,     //ik_max_word会对文本做最细力度的拆分
                            'search_analyzer' =>'ik_max_word'   //ik_smart--会对文本做最粗粒度的拆分
                        ],
                        'date' => [
                            'type'=> 'date',
                            'format' => 'yyyy-MM-dd HH:mm:ss'
                        ],
                        'category' => [
                            'type' => 'keyword',   //默认支持聚合
                            'ignore_above' => 256
                        ],
                        'author_name' =>[
                            'type' => 'text',
                            'analyzer' => 'ik_max_word' ,
                            'search_analyzer' =>'ik_smart' ,
                            'fields' => [                    //一般推荐这样进行聚合
                                'keyword' => [
                                    'type' => 'keyword'
                                ]
                            ]
                        ],
                        'url' =>[
                            'type' => 'keyword',  //string (丢弃）
                        ],
                        'thumbnail_pic' =>[
                            'properties' => [
                                'thumbnail_pic_s' => [
                                    'type' => 'keyword'
                                ],
                                'thumbnail_pic_s02' => [
                                    'type' => 'keyword'
                                ],
                                'thumbnail_pic_s03' => [
                                    'type' => 'keyword'
                                ]
                            ]
                        ],
                        'is_content' =>[
                            'type' => 'keyword',
                            'null_value'=> '0',  // 默认值 Keyword
                        ]
                    ]
                ]
            ]
        ];
        $response = array();
        try{
            $response = EsController::getInstance()->createMapping($params);
        }
        catch (Exception $exception)
        {
            $this->resultJson->setMessage($exception->getMessage());
        }
        finally{
            $this->resultJson->setData($response)->errorJson();//{ acknowledged: true }
        }
    }

    public function getMapping()
    {
        $params = [
            'index' => 'news',
            'type' => 'top'
        ];
        $response = array();
        try{
            $response = EsController::getInstance()->getMapping($params);
        }catch (Exception $exception)
        {
            $this->resultJson->setMessage($exception->getMessage());
        }
        finally{
            $this->resultJson->setData($response)->errorJson();//
        }
    }
    public function insertDataBulk()
    {
        $count = $page = 0;
        $params = array();
        $start_time = microtime(true);
        $data = new GetDataController();
        $result = $data->getBulkRequest(10);
        foreach ($result as $page => $single)          //组装数据  canal进行数据同步
        {
            if(!empty($single))
            {
                foreach ($single as $item)
                {
                    $params['body'][]=array(
                        'index' => array(                    // create-创建 index-创建或替换 update-局部更新
                            '_index' => 'news',
                            '_type' => 'top',
                            '_id'=>$item['uniquekey'],
                        ),
                    );
                    $params['body'][]=array(
                        'title'=>$item['title'],
                        'date' => $item['date'],
                        'category' => $item['category'],
                        'author_name' => $item['author_name'],
                        'url' => $item['url'],
                        'thumbnail_pic' =>[
                            'thumbnail_pic_s' => $item['thumbnail_pic_s'] ? $item['thumbnail_pic_s'] : '',
                            'thumbnail_pic_s02' => isset($item['thumbnail_pic_s02']) ? $item['thumbnail_pic_s02'] : '',
                            'thumbnail_pic_s03' => isset($item['thumbnail_pic_s03']) ? $item['thumbnail_pic_s03'] : '',
                        ],
                        'is_content' => $item['is_content']
                    );
                    $count++;
                }
            }
            $page++;
        }
        if(!empty($params))
        {
            $response = EsController::getInstance()->bulkData($params);
        }
        $end_time = microtime(true);
        $response['time'] = round((($end_time-$start_time)/1000),5);
        $response['page'] = $page;
        $response['count'] = $count;
        $this->resultJson->setData($response)->errorJson();
    }
    public function getSingleData($id)
    {
        $params = [
            'index' => 'news',
            'type' => 'top',
            'id' => $id
        ];
        $response = array();
        try{
            $response = EsController::getInstance()->getSingleById($params);
        }catch (Exception $exception)
        {
            $this->resultJson->setMessage($exception->getMessage());
        }
        finally{
            $this->resultJson->setData($response)->errorJson();//
        }
    }
    public function singleUpdate($id)
    {
        $params = [
            'index' => 'news',
            'type' => 'top',
            'id' => $id,
            'body' => [
                'doc' => [
                    'category' => '头条新闻'
                ]
            ]
        ];
        //updateByQuery  https://blog.csdn.net/zhanqixuan22/article/details/88964666
        try{
            $response = EsController::getInstance()->updateById($params);
            die(json_encode($response));
        }catch (Exception $exception)
        {
            die($exception->getMessage());
        }
    }

    //https://www.elastic.co/guide/cn/elasticsearch/guide/current/query-dsl-intro.html
    //https://www.elastic.co/guide/cn/elasticsearch/php/current/_search_operations.html
    // https://blog.csdn.net/laoyang360/article/details/80468757 query和filter
    public function queryData(Request $request)
    {
        $key_word = $request->get('keyword');
        if(empty($key_word))
        {
            die(json_encode(array('error' => 0,'message' => '请输入关键字')));
        }
        $query = [
            'index' => 'news',
            'type' => 'top',
            'body' => [
                'query' => [
                    'match' =>[
                        'title' => [
                            'query' =>$key_word,
                            'analyzer'=>'ik_max_word'
                        ]
                    ]
                ]
            ]
        ];
        try{
            $response = EsController::getInstance()->queryData($query);
            die(json_encode($response));
        }catch (Exception $exception)
        {
            die($exception->getMessage());
        }
    }
}